package com.sam.designpatterns;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 单例模式
 * Created by samwang on 2018/4/21.
 */
public class Singleton implements Serializable{
    private static Singleton instance;
    private Singleton(){}//构造器私有

    //懒汉模式
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    //双重检查
    public static Singleton getInstance2() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    //静态内部类
    public static Singleton getInstance3() {
        return SingletonHolder.instance;
    }
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();
    }

    private Object readResolve() {
        return instance;
    }


    enum SingletonEnum {
        INSTANCE;
    }

//    public class SignletonManager {
//        private static Map<String, Object> objMap = new HashMap<>();
//
//        private SignletonManager(){}
//
//        public static void registerservice(String key, Object instance) {
//            if (!objMap.containsKey(key)) {
//                objMap.put(key, instance);
//            }
//        }
//
//        public static Object getService(String key) {
//            return objMap.get(key);
//        }
//    }
}

